<?php

namespace app\api\controller;

use think\Exception;
use think\exception\FileException;
use app\common\library\Upload;
use app\common\controller\Frontend;

class Ajax extends Frontend
{
    protected $noNeedLogin = ['area', 'buildSuffixSvg'];

    public function initialize()
    {
        parent::initialize();
    }

    public function upload()
    {
        $file = $this->request->file('file');
        $attachment = null;
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload(null, 0, $this->auth->id);
            unset($attachment['createtime'], $attachment['quote']);
        } catch (Exception|FileException $e) {
            $upload = new Upload($file);
            $attachment = $upload->upload(null, 0, $this->auth->getUserId());
            // unset($attachment['createtime'], $attachment['quote']);
            $attachment = [
                'url' => $attachment['url'],
                'full_url' => $attachment['full_url'],
                'width' => $attachment['width'],
                'height' => $attachment['height'],
                'name' => $attachment['name'],
                'size' => $attachment['size'],
                'mimetype' => $attachment['mimetype'],
                'sha1' => $attachment['sha1'],
                'suffix' => $attachment['suffix'],
            ];
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('File uploaded successfully'), [
            'file' => $attachment ?? []
        ]);
        if (!$attachment) $this->error('上传失败');
        $this->success('上传成功', [
            'file' => $attachment,
        ]);
    }

    public function area()
    {
        $this->success('', get_area());
    }

    public function buildSuffixSvg()
    {
        $suffix = $this->request->param('suffix', 'file');
        $background = $this->request->param('background');
        $content = build_suffix_svg((string)$suffix, (string)$background);
        return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/svg+xml');
    }
}